package com.example.yyy

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_json.*
import org.json.JSONArray
import org.json.JSONObject

class JsonActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_json)
        var jsonStr1 = ""
        btn_ja_createJson.setOnClickListener {
            jsonStr1 = jsonStr
            tv_ja_json.text = jsonStr1
        }
        btn_ja_analysisJson.setOnClickListener {
            tv_ja_json.text = analysisJson(jsonStr1)
        }
        btn_ja_traversalsJson.setOnClickListener {
            tv_ja_json.text = traversalsJson(jsonStr1)
        }
        val goods = Goods(2,4,"2","4")
//        Gson().toJson(goods)
//        Gson().fromJson(jsonStr1,Goods::class.java)
    }

    /**
     * 创建Json串
     */
    private val jsonStr: String
    get() {
        val obj = JSONObject()
        obj.put("name","地址信息")
        val array = JSONArray()
        for (i in 0..5){
            val item = JSONObject()
            item.put("item","第$i 个元素")
            array.put(item)
        }
        obj.put("list",array)
        obj.put("count",array.length())
        obj.put("desc","只是Json串")

        return obj.toString()
    }

    /**
     * 解析Json串
     */
    private fun analysisJson(jsonStr: String?) :String{
        val obj = JSONObject(jsonStr)
        val result = StringBuffer()
        result.append("name=${obj.getString("name")}\n" +
                "desc=${obj.getString("desc")}\n" +
                "count=${obj.getString("count")}\n")
        val jsonArray = obj.getJSONArray("list")
        for ( i in 0 until  jsonArray.length()){
            result.append("item=${jsonArray.getJSONObject(i).getString("item")}")
        }

        return result.toString()
    }

    /**
     * 遍历Json
     */
    private fun traversalsJson(jsonStr: String?) :String{
        val obj = JSONObject(jsonStr)
        val it = obj.keys()
        val result = StringBuffer()
        while (it.hasNext()){
            var key = it.next().toString()
            result.append("key=$key, value=${obj.getString(key)}")
        }
        return result.toString()
    }
}